﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace Kaleta.Xna.Timing
{
    /// <summary>
    /// Defines a timeline container, e.g. groups timelines. After all timelines have finished, the storyboard fires Finished event.
    /// After initialization the storyboard is Stopped. After adding a timeline, the storyboard automatically starts itself and the timeline.
    /// </summary>
    public class Storyboard
    {
        public enum Playback
        {
            Stopped,
            Started,
            Paused,
        }
        private IList<ITimeline> Timelines { get; set; }
        public Playback State { get; set; }

        public event EventHandler Finished;

        public Storyboard()
        {
            Timelines = new List<ITimeline>();
            State = Playback.Stopped;
        }

        /// <summary>
        /// Adds this timeline. If the storyboard is not started, it will start. The timeline is automatically started.
        /// </summary>
        /// <param name="timeline"></param>
        /// <param name="automaticallyStart"></param>
        public void Add(ITimeline timeline)
        {
            Timelines.Add(timeline);

            timeline.Finished += new EventHandler<TimelineFinishedEventArgs>(timeline_Finished);

            State = Playback.Started;
            timeline.Start();
        }

        void timeline_Finished(object sender, TimelineFinishedEventArgs e)
        {
            Timelines.Remove(sender as ITimeline);
        }

        public void Pause()
        {
            if (State == Playback.Started)
                State = Playback.Paused;
        }

        public void Resume()
        {
            if (State == Playback.Paused)
                State = Playback.Started;
        }

        public void Update(GameTime gameTime)
        {
            if (State == Playback.Paused || State == Playback.Stopped) return;

            if (State == Playback.Started && Timelines.Count == 0)
            {
                State = Playback.Stopped;

                if (Finished != null)
                    Finished(this, null);
            }

            for (int i = Timelines.Count - 1; i >= 0; i--)
                Timelines[i].Update(gameTime);
        }
    }
}
